package code16_反射;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
 * @author 黄衡熙
 * @version 1.0
 */
public class Test06_解析注解 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException {
        Class c = Student.class;
        // 1.获取类上的所有注解
        Annotation[] annotations = c.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        System.out.println("************************************");

        // 2.获取类上指定注解
        Annotation someAnnotation = c.getAnnotation(SomeAnnotation.class);
        System.out.println(someAnnotation);
        System.out.println("************************************");

        // 3.获取指定属性上所有注解
        Field idField = c.getField("id");
        Annotation[] idAnnotations = idField.getAnnotations();
        for (Annotation annotation : idAnnotations) {
            System.out.println(annotation);
        }
        System.out.println("************************************");

        // 4.获取指定属性上指定注解
        OtherAnnotation idAnnotation = idField.getAnnotation(OtherAnnotation.class);
        System.out.println(idAnnotation);
        System.out.println("************************************");

        // 5.获取指定方法上所有注解
        Method method = c.getMethod("show");
        Annotation[] methodAnnotations = method.getAnnotations();
        for (Annotation annotation : methodAnnotations) {
            System.out.println(annotation);
        }
        System.out.println("************************************");

        // 6.获取指定方法上指定注解
        someAnnotation = method.getAnnotation(SomeAnnotation.class);
        System.out.println(someAnnotation);

        // 7.获取指定注解中指定属性的值
        SomeAnnotation someAnnotation2 = (SomeAnnotation) someAnnotation;
        System.out.println("name:" + someAnnotation2.name());
        System.out.println("value:" + Arrays.toString(someAnnotation2.value()));
        System.out.println("age:" + someAnnotation2.age());

        // 8.判断调用者是否使用了指定注解
        Field nameFiled = c.getField("name");
        if (nameFiled.isAnnotationPresent(SomeAnnotation.class)) {
            SomeAnnotation nameSomeAnnotation = nameFiled.getAnnotation(SomeAnnotation.class);
            System.out.println(nameSomeAnnotation);
        } else {
            System.out.println("name属性没有使用SomeAnnotation注解");
        }
        if (nameFiled.isAnnotationPresent(OtherAnnotation.class)) {
            OtherAnnotation otherAnnotation = nameFiled.getAnnotation(OtherAnnotation.class);
            System.out.println(otherAnnotation);
        } else {
            System.out.println("name属性没有使用OtherAnnotation注解");
        }

    }

}
